package com.xxc.hs.funActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.xxc.hs.R;
import com.xxc.hs.funActivity.panel.Answer;
import com.xxc.hs.funActivity.panel.AnswerDao;
import com.xxc.hs.funActivity.panel.EelFaqDatabase;
import com.xxc.hs.funActivity.panel.Expert;
import com.xxc.hs.funActivity.panel.ExpertDao;
import com.xxc.hs.funActivity.panel.Question;
import com.xxc.hs.funActivity.panel.QuestionAdapter;
import com.xxc.hs.funActivity.panel.QuestionDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@SuppressWarnings("ALL")
public class PanelActivity extends AppCompatActivity {

    private RecyclerView rvQuestions;
    private EditText etSearch;
    private LinearLayout llExpertPanel;
    private ImageView ivBack;
    private Button btnConsult;
    private TextView tvExpertAnswer;
    private QuestionAdapter questionAdapter;
    private List<Question> questionList;
    private QuestionDao questionDao;
    private ExpertDao expertDao;
    private AnswerDao answerDao;
    private Handler mainHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_panel);

        try {
            // 初始化数据库DAO
            questionDao = new QuestionDao(this);
            expertDao = new ExpertDao(this);
            answerDao = new AnswerDao(this);
            mainHandler = new Handler(Looper.getMainLooper());

            // 初始化视图组件
            initViews();

            // 初始化数据
            initData();

            // 设置RecyclerView
            setupRecyclerView();

            // 设置事件监听
            setupEventListeners();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initViews() {
        rvQuestions = findViewById(R.id.rv_common_questions);
        etSearch = findViewById(R.id.et_search);
        llExpertPanel = findViewById(R.id.ll_expert_panel);
        ivBack = findViewById(R.id.iv_back);
        btnConsult = findViewById(R.id.btn_consult);
        tvExpertAnswer = findViewById(R.id.tv_expert_answer);
        questionList = new ArrayList<>();
    }

    private void initData() {
        // 在后台线程中获取问题数据
        new Thread(() -> {
            List<Question> questions = questionDao.getAllQuestions();
            if (questions.isEmpty()) {
                // 如果数据库为空，插入示例数据
                EelFaqDatabase dbHelper = new EelFaqDatabase(this);
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                dbHelper.insertSampleData(db);
                db.close();

                // 重新获取数据
                questions = questionDao.getAllQuestions();
            }

            // 更新UI
            List<Question> finalQuestions = questions;
            mainHandler.post(() -> {
                questionList.clear();
                questionList.addAll(finalQuestions);
                questionAdapter.notifyDataSetChanged();
            });
        }).start();
    }

    private void setupRecyclerView() {
        rvQuestions.setLayoutManager(new LinearLayoutManager(this));
        questionAdapter = new QuestionAdapter(questionList, this);
        rvQuestions.setAdapter(questionAdapter);

        // 设置RecyclerView项点击事件
        questionAdapter.setOnItemClickListener(new QuestionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Question question) {
                // 在后台线程中获取详情数据并更新UI
                new Thread(() -> {
                    final Expert expert = expertDao.getExpertById(question.getExpertId());
                    final Answer answer = answerDao.getAnswerByQuestionId(question.getId());
                    mainHandler.post(() -> showExpertPanel(question, expert, answer));
                }).start();
            }
        });
    }

    private void setupEventListeners() {
        // 返回按钮点击事件
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 搜索框文本变化监听
        etSearch.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String query = s.toString().toLowerCase(Locale.getDefault());
                searchQuestions(query);
            }
        });

        // 咨询按钮点击事件
        btnConsult.setOnClickListener(v -> {
            Toast.makeText(PanelActivity.this, "咨询成功，请注意短信消息", Toast.LENGTH_SHORT).show();
            btnConsult.setText("咨询成功");
            // 这里可以添加跳转到咨询页面的代码
        });
    }

    private void searchQuestions(String query) {
        // 在后台线程中搜索问题
        new Thread(() -> {
            List<Question> questions;
            if (query.isEmpty()) {
                questions = questionDao.getAllQuestions();
            } else {
                questions = questionDao.searchQuestions(query);
            }

            // 更新UI
            mainHandler.post(() -> {
                questionList.clear();
                questionList.addAll(questions);
                questionAdapter.notifyDataSetChanged();
            });
        }).start();
    }

    private void showExpertPanel(Question question, Expert expert, Answer answer) {
        // 显示专家面板
        llExpertPanel.setVisibility(View.VISIBLE);

        if (expert != null) {
            // 填充专家基本信息
            TextView tvExpertName = findViewById(R.id.tv_expert_name);
            TextView tvExpertTitle = findViewById(R.id.tv_expert_title);
            TextView tvExpertRating = findViewById(R.id.tv_expert_rating);
            TextView tvConsultCount = findViewById(R.id.tv_consult_count);

            tvExpertName.setText(expert.getName() + " - 水产养殖专家");
            tvExpertTitle.setText(expert.getTitle());
            tvExpertRating.setText(String.format("%.1f", expert.getRating()));
            tvConsultCount.setText("(" + expert.getConsultCount() + "次问诊)");

            // 填充专家擅长领域
            LinearLayout llExpertSkills = findViewById(R.id.ll_expert_skills);
            llExpertSkills.removeAllViews();

            String[] skills = expert.getSkills().split(",");
            for (String skill : skills) {
                TextView tvSkill = new TextView(this);
                tvSkill.setText(skill.trim());
                tvSkill.setTextSize(14);
                tvSkill.setBackgroundResource(R.drawable.tag_bg);
                tvSkill.setPadding(8, 8, 8, 8);

                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                );
                params.setMargins(0, 0, 8, 8);
                tvSkill.setLayoutParams(params);

                llExpertSkills.addView(tvSkill);
            }
        }

        if (answer != null) {
            tvExpertAnswer.setText(answer.getContent());
        }


        // 滚动到专家面板位置
        rvQuestions.post(() -> rvQuestions.scrollToPosition(0));
    }

}


